<template>
  <el-config-provider :locale="zhCn">
    <div class="send-social">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="success" @click="handleCreateTask">新增任务</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="taskList" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="task_name" label="任务名称" min-width="150" />
          <el-table-column prop="type" label="发送类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.type === '1' ? 'primary' : 'success'">
                {{ row.type === '1' ? '立即发送' : '定时发送' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="execution_time" label="执行时间" width="180" />
          <el-table-column label="消息类型" width="150" align="center">
            <template #default="{ row }">
              <div class="message-type-tags">
                <template v-if="row.message_data">
                  <el-tag v-if="JSON.parse(row.message_data).text" type="info" class="message-type-tag"> 文本 </el-tag>
                  <el-tag v-if="JSON.parse(row.message_data).imgUrlList" type="warning" class="message-type-tag"> 图片 </el-tag>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="privacy" label="隐私设置" width="130">
            <template #default="scope">
              <el-tag :type="scope.row.privacy === '0' ? 'success' : 'info'">
                {{ scope.row.privacy === '0' ? '所有人可见' : '仅自己可见' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="任务状态" width="100">
            <template #default="scope">
              <el-tag
                :style="{
                  backgroundColor: scope.row.status === '2' ? '#67c23a' : '#409eff',
                  color: '#ffffff',
                  borderColor: scope.row.status === '2' ? '#67c23a' : '#409eff'
                }"
              >
                {{ scope.row.status === '1' ? '执行中' : '已完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_by_str" label="创建人" width="120" />
          <el-table-column prop="create_time" label="创建时间" width="180" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">{{ scope.row.status == '2' ? '查看' : '编辑' }}</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)" v-if="scope.row.status !== '2'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑任务对话框 -->
      <el-dialog v-model="taskDialogVisible" :title="getDialogTitle" width="80%" destroy-on-close class="task-dialog">
        <div style="display: flex; gap: 50px; height: 83vh; overflow: hidden">
          <div class="left-content">
            <el-form :model="taskForm" label-width="100px" class="task-form" :disabled="isViewMode">
              <el-form-item label="任务名称" required>
                <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
              </el-form-item>
              <el-form-item label="发送类型">
                <div class="material-section">
                  <div class="material-options">
                    <el-radio-group v-model="taskForm.sendType">
                      <el-radio label="realtime">实时发送</el-radio>
                      <el-radio label="scheduled">定时发送</el-radio>
                    </el-radio-group>
                    <el-date-picker
                      v-if="taskForm.sendType === 'scheduled'"
                      v-model="taskForm.scheduledTime"
                      type="datetime"
                      placeholder="选择发送时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :disabled="isViewMode"
                      :class="{ 'is-required': taskForm.sendType === 'scheduled' }"
                      :disabled-date="disabledBeforeToday"
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="隐私设置">
                <el-radio-group v-model="taskForm.isPrivate">
                  <el-radio label="0">所有人可见</el-radio>
                  <el-radio label="1">仅自己可见</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>

            <div class="content-type-section">
              <div class="section-title">内容类型</div>
              <el-tabs v-model="taskForm.contentType" class="content-tabs" :disabled="isViewMode">
                <el-tab-pane label="文本" name="text">
                  <el-form :model="taskForm" class="content-form">
                    <el-form-item label="文本内容" class="content-item">
                      <div class="content-input-wrapper">
                        <el-input
                          v-model="taskForm.content"
                          type="textarea"
                          :rows="4"
                          placeholder="请输入朋友圈内容"
                          ref="contentTextArea"
                          :disabled="isViewMode"
                          maxlength="2000"
                          show-word-limit
                        />
                        <div class="emoji-trigger" @click="toggleEmojiPicker" v-if="!isViewMode">
                          <el-icon class="emoji-icon"><ChatDotRound /></el-icon>
                        </div>
                        <div v-if="showEmojiPicker" ref="emojiPickerRef" class="emoji-picker-container">
                          <EmojiPicker class="emoji-picker" :i18n="zhConfig" @select="onSelectEmoji" />
                        </div>
                      </div>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
                <!-- <el-tab-pane label="图片" name="image">
                  <el-form :model="taskForm" class="content-form">
                    <el-form-item label="图片内容">
                      <el-upload
                        action="#"
                        list-type="picture-card"
                        :auto-upload="false"
                        :on-change="handleImageChange"
                        :on-remove="handleImageRemove"
                        :limit="9"
                        :file-list="fileList"
                        :disabled="isViewMode"
                        accept="image/*"
                      >
                        <el-icon><Plus /></el-icon>
                        <template #tip>
                          <div class="el-upload__tip">
                            <el-icon class="tip-icon"><InfoFilled /></el-icon>
                            <span>最多上传9张图片</span>
                          </div>
                        </template>
                      </el-upload>
                    </el-form-item>
                  </el-form>
                </el-tab-pane> -->
                <!-- <el-tab-pane label="视频" name="video">
                  <el-form :model="taskForm" class="content-form">
                    <el-form-item label="视频内容">
                      <el-upload
                        class="video-uploader"
                        action="#"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="handleVideoChange"
                        :on-remove="handleVideoRemove"
                        accept=".mp4"
                        :limit="1"
                        :disabled="isViewMode"
                      >
                        <video v-if="taskForm.videoUrl" :src="taskForm.videoUrl" class="preview-video" controls />
                        <el-icon v-else class="upload-icon"><Plus /></el-icon>
                      </el-upload>
                    </el-form-item>
                  </el-form>
                </el-tab-pane> -->
              </el-tabs>
            </div>
          </div>
          <div class="right-content">
            <div class="right-content-preview">
              <div class="preview-cover">
                <img :src="coverDefault" alt="cover" />
                <div class="preview-user-info">
                  <div class="preview-user-meta">
                    <div class="preview-age">{{ nickname }}</div>
                  </div>
                  <img class="preview-avatar" :src="avatarSrc" alt="avatar" />
                </div>
              </div>
              <div class="preview-post-container" v-if="taskForm.content || taskForm.images.length || taskForm.video">
                <img class="preview-avatar" :src="avatarSrc" alt="avatar" />
                <div class="preview-content">
                  <div class="preview-nickname">{{ nickname }}</div>
                  <div class="preview-content-card">
                    <div v-if="taskForm.content" class="preview-text">{{ taskForm.content }}</div>
                    <div v-if="taskForm.images.length" class="preview-image-grid" :class="getImageGridClass(taskForm.images.length)">
                      <div v-for="(image, index) in taskForm.images" :key="index" class="preview-image-item">
                        <img :src="image.previewUrl || URL.createObjectURL(image.raw)" />
                      </div>
                    </div>
                    <div v-if="taskForm.video" class="preview-video">
                      <video :src="URL.createObjectURL(taskForm.video)" controls />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="taskDialogVisible = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
            <el-button type="primary" @click="submitTask" v-if="!isViewMode">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox, ElInput } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import EmojiPicker from 'vue3-emoji-picker';
import { ChatDotRound, InfoFilled, Plus } from '@element-plus/icons-vue';
import 'vue3-emoji-picker/css';
import { uploadEncryptedMomentsImage, sendTextImageMoments, updateMomentsTask, getMomentsTaskList, deleteMomentsTask } from '@/api/friendSocial/sendSocial';
import coverDefault from '@/assets/bg.jpg';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import { useUserStore } from '@/store/modules/user';
import defaultAvatar from '@/assets/avatar.jpg';

// 定义响应类型
interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 定义 URL 对象
const URL = window.URL || window.webkitURL;

// 获取文本区域的引用
const contentTextArea = ref<InstanceType<typeof ElInput> | null>(null);

interface Task {
  task_id: number;
  task_name: string;
  create_by: string;
  create_time: string;
  execution_time: string;
  status: string;
  privacy: '0' | '1';
  message_data: string;
  is_delete: string;
  type: string;
}

interface ImageItem {
  url: string;
  previewUrl: string;
  raw: File;
}

interface TaskForm {
  taskName: string;
  sendType: string;
  scheduledTime: string;
  contentType: string;
  content: string;
  images: ImageItem[];
  video: File | null;
  videoUrl?: string | null;
  isPrivate: '0' | '1';
}

interface SendParams {
  text: string;
  imgUrlList: string;
  umUrlList: string;
  isPrivate: '0' | '1';
  wxId: string;
  taskName: string;
  type: string;
  executionTime: string;
  taskId?: string;
  account: string;
}

// 筛选表单配置
const formItems: FormItem[] = [
  {
    type: 'input',
    label: '任务名称',
    prop: 'taskName',
    placeholder: '请输入任务名称',
    clearable: true
  },
  {
    type: 'select',
    label: '任务状态',
    prop: 'status',
    placeholder: '请选择任务状态',
    clearable: true,
    options: [
      { label: '执行中', value: '1' },
      { label: '已完成', value: '2' }
    ]
  },
  {
    type: 'select',
    label: '隐私设置',
    prop: 'privacy',
    placeholder: '请选择隐私设置',
    clearable: true,
    options: [
      { label: '所有人可见', value: '0' },
      { label: '仅自己可见', value: '1' }
    ]
  },
  {
    type: 'select',
    label: '任务类型',
    prop: 'type',
    placeholder: '请选择任务类型',
    clearable: true,
    options: [
      { label: '实时', value: '1' },
      { label: '定时', value: '2' }
    ]
  }
];

// 筛选表单
const filterForm = reactive({
  taskName: '',
  status: '',
  privacy: '',
  type: ''
});

// 任务列表数据
const taskList = ref<Task[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 新增任务对话框
const taskDialogVisible = ref(false);
const taskForm = reactive<TaskForm & { videoUrl?: string | null }>({
  taskName: '',
  sendType: 'realtime',
  scheduledTime: '',
  contentType: 'text',
  content: '',
  images: [],
  video: null,
  videoUrl: '',
  isPrivate: '0'
});

// 添加emoji选择器显示状态
const showEmojiPicker = ref(false);
const emojiPickerRef = ref<HTMLElement | null>(null);

// 中文配置
const zhConfig = {
  search: '搜索表情',
  categories: {
    recents: '最近使用',
    smileys: '表情符号',
    people: '人物',
    animals: '动物',
    food: '食物',
    activities: '活动',
    travel: '旅行',
    objects: '物品',
    symbols: '符号',
    flags: '旗帜',
    custom: '自定义'
  },
  notFound: '未找到表情'
};

// 添加 wxId 变量
const wxId = ref('');

// 添加编辑状态标记
const isEdit = ref(false);
const currentTask = ref<Task | null>(null);

// 添加 fileList 响应式变量
const fileList = ref<any[]>([]);

// 添加查看模式标记
const isViewMode = ref(false);

// 在 script setup 中添加
const userStore = useUserStore();
const avatarSrc = computed(() => userStore.userInfo.avatar || defaultAvatar);
const nickname = computed(() => userStore.userInfo.name || '未命名');
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
const account = userInfo.username || '';

// 处理点击外部区域关闭选择器
const handleClickOutside = (event: MouseEvent) => {
  if (showEmojiPicker.value && emojiPickerRef.value) {
    const target = event.target as HTMLElement;
    if (!emojiPickerRef.value.contains(target) && !target.closest('.emoji-trigger')) {
      showEmojiPicker.value = false;
    }
  }
};

// 添加和移除全局点击事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  // 初始化 wxId
  wxId.value = JSON.parse(localStorage.getItem('msgprofile') || '{}').wx_id || '';
  handleSearch();
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 切换emoji选择器显示状态
const toggleEmojiPicker = (event: MouseEvent) => {
  event.stopPropagation();
  // ElMessage.info('表情选择功能正在开发中，敬请期待！');
  showEmojiPicker.value = !showEmojiPicker.value;
};

// 修改表情选择处理方法
const onSelectEmoji = (emoji: { i: string }) => {
  if (contentTextArea.value) {
    const textarea = contentTextArea.value.$el.querySelector('textarea');
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const text = taskForm.content;
      const newText = text.substring(0, start) + emoji.i + text.substring(end);

      // 检查字数限制
      if (newText.length > 2000) {
        ElMessage.warning('添加表情后内容将超过2000个字符限制');
        showEmojiPicker.value = false;
        return;
      }

      taskForm.content = newText;
      // 插入表情后，将光标设置到表情后面
      nextTick(() => {
        textarea.selectionStart = textarea.selectionEnd = start + emoji.i.length;
        textarea.focus();
      });
    }
  }
  // 选择完表情后关闭选择器
  showEmojiPicker.value = false;
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.taskName = val.taskName || '';
  filterForm.status = val.status || '';
  filterForm.privacy = val.privacy || '';
  filterForm.type = val.type || '';
};

// 搜索方法
const handleSearch = async () => {
  try {
    loading.value = true;
    // 构建参数对象，移除空字符串参数
    const paramsObj: Record<string, any> = {
      taskName: filterForm.taskName,
      status: filterForm.status,
      privacy: filterForm.privacy,
      type: filterForm.type,
      wxId: wxId.value,
      current: currentPage.value,
      size: pageSize.value
    };
    Object.keys(paramsObj).forEach((key) => {
      if (paramsObj[key] === '') delete paramsObj[key];
    });
    const response = await getMomentsTaskList(paramsObj);

    const apiResponse = response as unknown as ApiResponse<{
      records: Task[];
      total: number;
      size: number;
      current: number;
    }>;

    if (apiResponse.code === 200) {
      taskList.value = apiResponse.data.records;
      total.value = apiResponse.data.total;
      currentPage.value = apiResponse.data.current;
      pageSize.value = apiResponse.data.size;
    } else {
      ElMessage.error(apiResponse.msg || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  // 重置筛选条件
  Object.keys(filterForm).forEach((key) => {
    (filterForm as any)[key] = '';
  });
  // 重置分页参数
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 处理分页变化
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};
const disabledBeforeToday = (time: any) => {
  // 禁用今天及之前的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
};

// 新增任务
const handleCreateTask = () => {
  isEdit.value = false;
  currentTask.value = null;
  isViewMode.value = false; // 新增任务时不是查看模式
  taskDialogVisible.value = true;
  taskForm.taskName = '';
  taskForm.sendType = 'realtime';
  taskForm.scheduledTime = '';
  taskForm.content = '';
  taskForm.images = [];
  taskForm.video = null;
  taskForm.videoUrl = '';
  taskForm.isPrivate = '0';
  fileList.value = [];
};

// 编辑任务
const handleEdit = (task: Task) => {
  isEdit.value = true;
  currentTask.value = task;
  taskDialogVisible.value = true;
  isViewMode.value = task.status === '2'; // 如果任务已完成，设置为查看模式

  // 解析消息数据
  const messageData = JSON.parse(task.message_data);

  // 填充表单数据
  taskForm.taskName = task.task_name;
  taskForm.sendType = task.type === '1' ? 'realtime' : 'scheduled';
  taskForm.scheduledTime = task.execution_time;
  taskForm.isPrivate = task.privacy as '0' | '1';
  taskForm.content = messageData.text || '';

  // 如果有图片，需要重新获取图片
  if (messageData.imgUrlList && messageData.umUrlList) {
    const imgUrls = messageData.imgUrlList.split(',');
    const umUrls = messageData.umUrlList.split(',');
    taskForm.images = imgUrls.map((url: string, index: number) => ({
      url,
      previewUrl: import.meta.env.VITE_GLOB_APP_IMG_URL + umUrls[index],
      raw: new File([], '') // 这里需要重新获取图片文件
    }));
    // 设置 fileList
    fileList.value = imgUrls.map((url: string, index: number) => ({
      name: `image-${index + 1}`,
      url: import.meta.env.VITE_GLOB_APP_IMG_URL + umUrls[index]
    }));
    // 设置内容类型为图片
    taskForm.contentType = 'image';
  } else {
    // 如果没有图片，设置为文本类型
    taskForm.contentType = 'text';
    fileList.value = [];
  }
};

// 修改提交任务方法
const submitTask = async () => {
  try {
    if (!taskForm.taskName) {
      ElMessage.warning('请输入任务名称');
      return;
    }

    if (taskForm.sendType === 'scheduled' && !taskForm.scheduledTime) {
      ElMessage.warning('请选择发送时间');
      return;
    }

    if (taskForm.contentType === 'text' && !taskForm.content) {
      ElMessage.warning('请输入文本内容');
      return;
    }

    if (taskForm.contentType === 'text' && taskForm.content && taskForm.content.length > 2000) {
      ElMessage.warning('文本内容不能超过2000个字符');
      return;
    }

    if (taskForm.contentType === 'image' && taskForm.images.length === 0) {
      ElMessage.warning('请上传图片');
      return;
    }

    // 构建发送参数
    const params: SendParams = {
      text: taskForm.content || '',
      imgUrlList: taskForm.images.map((img) => img.url).join(','),
      umUrlList: taskForm.images.map((img) => img.previewUrl.replace(import.meta.env.VITE_GLOB_APP_IMG_URL, '')).join(','),
      isPrivate: taskForm.isPrivate,
      wxId: wxId.value,
      taskName: taskForm.taskName,
      type: taskForm.sendType === 'realtime' ? '1' : '2',
      executionTime: taskForm.sendType === 'scheduled' ? taskForm.scheduledTime : '',
      account: account
    };

    let response;
    if (isEdit.value && currentTask.value) {
      // 编辑模式 - 调用更新接口
      params.taskId = currentTask.value.task_id.toString();
      response = await updateMomentsTask(params);
    } else {
      // 新增模式 - 调用发送接口
      response = await sendTextImageMoments(params);
    }

    const apiResponse = response as unknown as ApiResponse;
    if (apiResponse.code === 200) {
      ElMessage.success(isEdit.value ? '编辑成功' : '发送成功');
      taskDialogVisible.value = false;
      handleSearch(); // 刷新列表
    } else {
      ElMessage.error(apiResponse.msg || (isEdit.value ? '编辑失败' : '发送失败'));
    }
  } catch (error) {
    console.error(isEdit.value ? '编辑失败:' : '发送失败:', error);
    ElMessage.error(isEdit.value ? '编辑失败' : '发送失败');
  }
};

// 删除任务
const handleDelete = async (task: Task) => {
  try {
    await ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteMomentsTask(task.task_id.toString());
    const apiResponse = response as unknown as ApiResponse;
    if (apiResponse.code === 200) {
      ElMessage.success('删除成功');
      handleSearch();
    } else {
      ElMessage.error(apiResponse.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 图片上传相关方法
const handleImageChange = async (file: any) => {
  // 图片格式限制
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('只支持 JPG、PNG、GIF、WEBP 格式的图片');
    return;
  }
  try {
    // 上传图片
    const response: any = await uploadEncryptedMomentsImage(file.raw, wxId.value);
    if (response.code === 200) {
      // 上传成功，将图片URL添加到列表中
      taskForm.images.push({
        url: response.data.imgUrlList,
        previewUrl: import.meta.env.VITE_GLOB_APP_IMG_URL + response.data.umUrlList,
        raw: file.raw
      });
      console.log(taskForm.images);

      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(response?.msg || '图片上传失败');
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    ElMessage.error('图片上传失败');
  }
};

const handleImageRemove = (file: any) => {
  // 使用 url 来匹配图片，因为编辑时 raw 可能是空的
  const index = taskForm.images.findIndex((img: ImageItem) => {
    if (file.url) {
      // 如果是编辑时的删除，使用 url 匹配
      return img.previewUrl === file.url;
    } else {
      // 如果是新上传的删除，使用 raw 匹配
      return img.raw === file.raw;
    }
  });

  if (index !== -1) {
    taskForm.images.splice(index, 1);
    fileList.value.splice(index, 1);
  }
  console.log(taskForm.images);
  console.log(fileList.value);
};

// 视频上传相关方法
const handleVideoChange = async (event: { raw: File }) => {
  if (event.raw) {
    // 检查文件类型
    if (!event.raw.type.includes('mp4') && !event.raw.name.toLowerCase().endsWith('.mp4')) {
      ElMessage.error('只支持MP4格式的视频文件');
      return;
    }
    try {
      // 假设有uploadEncryptedMomentsImage或uploadFile接口可用
      const response: any = await uploadEncryptedMomentsImage(event.raw, wxId.value);
      if (response.code === 200 && response.data) {
        taskForm.videoUrl = import.meta.env.VITE_GLOB_APP_IMG_URL + response.data;
        ElMessage.success('视频上传成功');
      } else {
        ElMessage.error(response?.msg || '视频上传失败');
      }
    } catch (error) {
      console.error('视频上传失败:', error);
      ElMessage.error('视频上传失败');
    }
  }
};

const handleVideoRemove = () => {
  taskForm.videoUrl = '';
};

// 添加获取图片网格类名的方法
const getImageGridClass = (count: number) => {
  return `grid-${count}`;
};

// 获取对话框标题
const getDialogTitle = computed(() => {
  return isEdit.value ? '编辑任务' : '新增任务';
});
</script>

<style lang="scss" scoped>
.send-social {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.task-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__header) {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    background: #f5f7fa;
  }

  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }

  :deep(.el-dialog__headerbtn) {
    top: 20px;
  }

  .task-form {
    padding: 0 24px;
    background: #fff;

    .el-form-item {
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #303133;
        padding-right: 16px;
      }

      :deep(.el-form-item__content) {
        .el-input__wrapper,
        .el-textarea__inner {
          box-shadow: 0 0 0 1px #dcdfe6 inset;
          transition: all 0.3s;

          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc inset;
          }

          &:focus {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
      }
    }

    .material-section {
      .material-options {
        display: flex;
        gap: 24px;
        align-items: center;

        .el-radio-group {
          display: flex;
          gap: 24px;

          :deep(.el-radio) {
            margin-right: 13px;
          }
        }

        .el-date-picker {
          width: 240px;

          &.is-required {
            :deep(.el-input__wrapper) {
              box-shadow: 0 0 0 1px #f56c6c inset;
            }
          }
        }
      }
    }

    .content-tabs {
      :deep(.el-tabs__content) {
        padding: 20px 0;
      }
    }

    .upload-tip {
      margin-top: 8px;
      color: #909399;
      font-size: 12px;
      text-align: center;

      .el-icon {
        font-size: 14px;
        color: #909399;
        margin-right: 4px;
      }
    }

    .mt-2 {
      margin-top: 8px;
    }
  }

  .left-content {
    padding: 0 20px;
    width: 75%;
    overflow-y: auto;
  }

  .right-content {
    width: 25%;
    background: #f6f8fa;
    border-radius: 30px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
    border: 1px solid #e5e7eb;
    padding: 10px;
    position: relative;
    height: 100%;
    overflow: hidden;
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40%;
      height: 20px;
      background: #e5e7eb;
      border-radius: 0 0 10px 10px;
    }

    .right-content-title {
      padding: 20px;
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
      border-bottom: 1px solid #e5e7eb;
      background: #ffffff;
    }

    .right-content-preview {
      padding: 0;
      background: #f6f8fa;
      .preview-cover {
        width: 100%;
        height: 180px;
        overflow: hidden;
        border-radius: 18px 18px 0 0;
        position: relative;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          display: block;
        }
        .preview-user-info {
          display: flex;
          align-items: center;
          padding: 16px;
          position: absolute;
          bottom: 0;
          right: 0;
          // background: linear-gradient(to top, rgba(0, 0, 0, 0.5), transparent);
          .preview-avatar {
            width: 50px;
            height: 50px;
            border-radius: 10px;
            border: 2px solid #fff;
            margin-left: auto;
            object-fit: cover;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
          }
          .preview-user-meta {
            margin-right: 16px;
            text-align: right;
            .preview-nickname {
              font-size: 16px;
              font-weight: 600;
              color: #fff;
              text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            }
            .preview-age {
              font-size: 14px;
              color: #fff;
              margin-top: 4px;
              // background: rgba(0, 0, 0, 0.3);
              padding: 2px 8px;
              border-radius: 4px;
              display: inline-block;
            }
          }
        }
      }
      .preview-post-container {
        display: flex;
        padding: 16px;
        gap: 12px;
        align-items: flex-start;

        .preview-avatar {
          width: 46px;
          height: 46px;
          border-radius: 8px;
          object-fit: cover;
          flex-shrink: 0;
          border: 2px solid #fff;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

        .preview-content {
          flex: 1;
          min-width: 0;

          .preview-nickname {
            font-size: 15px;
            font-weight: 500;
            color: #333;
            margin-bottom: 8px;
          }

          .preview-content-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            padding: 12px;
            .preview-time {
              font-size: 12px;
              color: #aaa;
              margin-bottom: 8px;
            }
            .preview-text {
              font-size: 15px;
              color: #222;
              margin-bottom: 12px;
              white-space: pre-wrap;
            }
            .preview-image-grid {
              display: grid;
              gap: 4px;
              margin-bottom: 12px;
              &.grid-1 {
                grid-template-columns: 1fr;
              }
              &.grid-2 {
                grid-template-columns: repeat(2, 1fr);
              }
              &.grid-3 {
                grid-template-columns: repeat(3, 1fr);
              }
              &.grid-4 {
                grid-template-columns: repeat(2, 1fr);
              }
              &.grid-5,
              &.grid-6 {
                grid-template-columns: repeat(3, 1fr);
              }
              &.grid-7,
              &.grid-8,
              &.grid-9 {
                grid-template-columns: repeat(3, 1fr);
              }
              .preview-image-item {
                aspect-ratio: 1;
                border-radius: 6px;
                overflow: hidden;
                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
              }
            }
            .preview-video {
              margin-bottom: 12px;
              video {
                width: 100%;
                max-width: 300px;
                border-radius: 8px;
              }
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    padding: 10px 24px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      padding: 8px 20px;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.content-type-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 20px;
    padding-left: 12px;
    border-left: 4px solid #409eff;
  }

  .content-tabs {
    :deep(.el-tabs__nav-wrap) {
      padding: 0 12px;
    }

    // :deep(.el-tabs__content) {
    //   padding: 20px 12px;
    // }
    :deep(.el-tabs__header) {
      margin-bottom: 24px;
    }
  }

  .content-form {
    .content-item {
      :deep(.el-form-item__content) {
        display: block;
      }
      .emoji-picker-container {
        background: #fff;
        border-radius: 8px;
        width: 350px;
        height: 400px;
        .emoji-picker {
          margin: 0;
          height: 100%;
          width: 100%;
        }
      }
      .el-form-item {
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #303133;
          padding-right: 16px;
        }

        :deep(.el-form-item__content) {
          .el-input__wrapper,
          .el-textarea__inner {
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            transition: all 0.3s;

            &:hover {
              box-shadow: 0 0 0 1px #c0c4cc inset;
            }

            &:focus {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
      }
    }
  }
}

.content-input-wrapper {
  position: relative;

  .emoji-trigger {
    position: absolute;
    right: 8px;
    top: 8px;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
    z-index: 2;

    &:hover {
      background-color: #f5f7fa;
    }

    .emoji-icon {
      font-size: 20px;
      color: #606266;
    }
  }
}

.el-upload__tip {
  display: flex;
  align-items: center;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;

  .tip-icon {
    font-size: 14px;
    margin-right: 4px;
  }
}
:deep(.el-overlay) {
  .task-dialog {
    --el-dialog-margin-top: 1vh !important;
  }
}
.message-type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;

  .message-type-tag {
    margin: 2px;
  }
}

.video-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
  &:hover {
    border-color: #409eff;
    background: #f5f7fa;
  }
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    transition: all 0.3s;
  }
  &:hover .upload-icon {
    color: #409eff;
  }
  .preview-video {
    width: 100%;
    max-height: 100px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}
</style>
